public class Solution606 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    String ans="";

    public String tree2str(TreeNode root) {
        ans=ans.concat(String.valueOf(root.val));
        if (root.left==null && root.right==null){
            return ans;
        }
        if (root.left==null){
            ans=ans.concat("()");
        }else {
            ans=ans.concat("(");
            tree2str(root.left);
            ans=ans.concat(")");
        }
        if (root.right!=null){
            ans=ans.concat("(");
            tree2str(root.right);
            ans=ans.concat(")");
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution606().tree2str(new TreeNode(1,new TreeNode(2,null,new TreeNode(3)),new TreeNode(4))));
    }
}
